package com.langsheng.lsintell.ui.fragment;


import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.langsheng.lsintell.R;
import com.langsheng.lsintell.cmd.request.LSRequest;
import com.langsheng.lsintell.config.LSLoginInfos;
import com.langsheng.lsintell.data.LSShopListReq;
import com.langsheng.lsintell.data.LSShopListRes;
import com.langsheng.lsintell.interfaces.LSResDataListener;
import com.langsheng.lsintell.network.LSNet;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LSShopFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LSShopFragment extends LSBaseFragment {
    private MapView mvMap;

    private AMap aMap;

    private double longitude;
    private double latitude;

    public LSShopFragment() {
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment LSShopFragment.
     */
    public static LSShopFragment newInstance() {
        LSShopFragment fragment = new LSShopFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lsshop, container, false);
        mvMap = (MapView) view.findViewById(R.id.mv_map);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mvMap.onCreate(savedInstanceState);
        aMap = mvMap.getMap();
        locateSelf();
    }

    private void locateSelf() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeWidth(0f);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                Log.e("onMyLocationChange", "latitude = " + latitude + ", longitude = " + longitude);
                doGetShopList();
            }
        });
    }

    private void doGetShopList() {
        if (LSLoginInfos.getOurInstance().getLoginData() == null) {
            return;
        }
        final LSRequest request = new LSRequest() {
            @Override
            public void createCmd() {
                setCmdCode(0x2020);
                LSShopListReq req = new LSShopListReq();
                req.setToken(LSLoginInfos.getOurInstance().getLoginData().getToken());
                req.setLatitude(latitude + "");
                req.setLongitude(longitude + "");
                setContent(JSONObject.toJSON(req).toString());
            }
        };

        LSNet.getInstance().sendRequest(request, true, new LSResDataListener() {
            @Override
            public boolean onResponse(String content) {
                LSShopListRes response = JSONObject.parseObject(content, LSShopListRes.class);
                addMarker(response.getRecords());
                return false;
            }

            @Override
            public boolean onResponseErr(String errCode, String content) {
                return false;
            }
        });
    }

    private void addMarker(LSShopListRes.RecordsBean data) {
        if (data != null) {
            List<LSShopListRes.RecordsBean.ABean> dataList = data.getA();
            for (LSShopListRes.RecordsBean.ABean aBean : dataList) {
                try {
                    LatLng latlng = new LatLng(Long.valueOf(aBean.getS7()), Long.valueOf(aBean.getS6()));
                    aMap.addMarker(new MarkerOptions().position(latlng).title(aBean.getS1()).snippet(aBean.getS3()).draggable(true)).showInfoWindow();
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mvMap.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mvMap.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mvMap.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mvMap.onSaveInstanceState(outState);
    }

}
